import webapp2
import datetime
import sys
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app

class ChatMessage(db.Model):
    timestamp = db.DateTimeProperty(auto_now_add = True)
    message = db.TextProperty(required = True)
    user = db.StringProperty(required = True)
    
    def __str__(self):
        return "%s (%s): %s\n" % (self.user, self.timestamp, self.message)

class ChatRoomPage(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user is None:
            self.redirect(users.create_login_url(self.request.url))
        else:
            self.response.headers["Content-Type"] = "text/html"
            self.response.out.write("""
                <html>
                <head>
                    <title>Welcome wayne's chatroom</title>
                </head>

                <body>
                    <h1>This is waye's chatroom</h1>
                    <p>Current time: %s</p>
                    <p> Anything you would contact bonushaw@163.com</p>
                """ % (datetime.datetime.now()))

            # output all message
            #messages = db.GqlQuery("SELECT * From ChatMessage ORDER BY timestamp")
            messages = ChatMessage.gql("ORDER BY timestamp")
            for msg in messages:
                self.response.out.write("<p>%s</p" % msg)

            self.response.out.write("""
                <form action = "/" method = "post">
                <p><b>Enter new message from %s</b></p>
                <p><b>Message</b></p>
                <div><textarea name = "message" rows = "10" cols = "60"></textarea></div>
                <div><input type = "submit" value = "send"/></div>
                </form>
            </body>
            </html>
            """ % user.nickname())

    def post(self):
        user = users.get_current_user()
        if user is None:
            self.redirect(users.create_login_url(self.request.url))        
        user = users.get_current_user()
        msgtext = self.request.get("message")
        if user.nickname() is None or user.nickname() == "":
            nick = "No nickname"
        else:
            nick = user.nickname()
        msg = ChatMessage(user = user.nickname(), message = msgtext)
        msg.put()
        sys.stderr.write("****** Just stored message: %s" % msg)
        self.redirect("/")


chatapp = webapp2.WSGIApplication([("/", ChatRoomPage)])

def main():
    run_wsgi_app(chatapp)

if __name__ == "__main__":
    main()
